const isElementsBothLoaded = async (selector1, selector2) => {
    while (document.querySelector(selector1) === null || document.querySelector(selector2) === null) {
        await new Promise(resolve => requestAnimationFrame(resolve))
    }
    let element1 = document.querySelector(selector1);
    let element2 = document.querySelector(selector2);
    return [element1, element2];
};

isElementsBothLoaded('.js-target-branch', '.sidebar-context-title').then((elements) => {
    // Run code here.
    let set = document.querySelector(".nav-item-name.qa-settings-item");
    if (set === null) {
        console.log("当前用户没有权限，不显示操作按钮");
        return;
    }

    // 目标分支
    const targetBranch = elements[0].innerText;
    // console.log('目标分支[' + targetBranch + ']');

    // 工程
    const project = elements[1].innerText;
    // console.log("工程[" + project + "]");

    let body = document.querySelector("body");
    let projectId = body.getAttribute("data-project-id");
    // console.log("projectId = " + projectId);


    // create button
    var openspan = document.createElement("span");
    openspan.className = 'gl-button-text';
    openspan.textContent = '打开';
    var open = document.createElement("button");
    open.setAttribute("type", "button");
    open.setAttribute("id", "openMerge");
    open.className = 'btn mr-3 btn-success btn-md gl-button';
    open.appendChild(openspan);

    var closespan = document.createElement("span");
    closespan.className = 'gl-button-text';
    closespan.textContent = '关闭';
    var close = document.createElement("button");
    close.setAttribute('type', 'button');
    close.setAttribute('id', 'closeMerge');
    close.className = 'btn mr-3 btn-warning btn-md gl-button';
    close.appendChild(closespan);

    var location = document.querySelector(".git-merge-container.d-flex .normal");
    var disableMerge = document.querySelector(".js-disabled-merge-button.btn.btn-success.btn-sm");
    if (disableMerge === null) {
        location.appendChild(close);
    } else {
        location.appendChild(open);
    }

    let protectQryUrl = window.location.protocol + "//" + window.location.host + "/api/v4/projects/" + projectId +
        "/protected_branches/" + targetBranch;

    // get protect id
    axios.get(protectQryUrl).then((response) => {
        let protectId = parseInt(response.data.id);
        // console.log('protectId = ' + protectId);
        if (isNaN(protectId)) {
            console.log("protectId is NaN");
            return;
        }

        // 获取当前页面的完整 URL
        let url = window.location.href;
        let parts = url.split('/-/');
        let firstPart = parts[0];

        let patchUrl = firstPart + "/-/protected_branches/" + protectId;
        // console.log('patch url = ' + patchUrl);

        let csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        // 绑定 open
        $('#openMerge').on('click', function () {
            // console.log('openMerge clicked !');
            axios.patch(patchUrl, {
                protected_branch: {
                    merge_access_levels_attributes: [{id: protectId, access_level: '40'}],
                    push_access_levels_attributes: [{id: protectId, access_level: '0'}]
                }
            }, {headers: {
                    'x-csrf-token': csrfToken,
                    'Content-Type': 'application/json;charset=UTF-8',
                    'x-requested-with': 'XMLHttpRequest'
                }}).then(() => {
                chrome.runtime.sendMessage({action: 'reload'}, (response) => {
                    // console.log('refresh current tab after open');
                });
            }).catch(() => {
                console.log('open protect failed');
            });
        });

        // 绑定 close
        $('#closeMerge').on('click', function () {
            // console.log('closeMerge clicked !');
            axios.patch(patchUrl, {
                protected_branch: {
                    merge_access_levels_attributes: [{id: protectId, access_level: '0'}],
                    push_access_levels_attributes: [{id: protectId, access_level: '0'}]
                }
            }, {headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'x-csrf-token': csrfToken,
                    'x-requested-with': 'XMLHttpRequest'
                }}).then(() => {
                chrome.runtime.sendMessage({action: 'reload'}, (response) => {
                    // console.log('refresh current tab after close');
                });
            }).catch(() => {
                console.log('close protect failed');
            });
        });
    }).catch((error) => {
        console.log('query protect id failed');
    });

});

